<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta
			name="viewport"
			content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
		/>
		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<title>message</title>
	</head>

	<body>
		<h1>WebView onAlert Demo</h1>
		<div>
			<input
				type="button"
				value="SendToEts"
				onclick="PostMsgToEts(msgFromJS.value);"
			/><br />
			<input id="msgFromJS" type="text" value="message from HTML" /><br />
		</div>
		<p id="output">display received message send from ets</p>
	</body>
	<script>
		var h5Port;
		var output = document.querySelector('#output');
		window.addEventListener('message', function (event) {
			if (event.data == '__init_port__') {
				console.log('get msg __init_port__');
				if (event.ports[0] != null) {
					h5Port = event.ports[0]; // 1. 保存从ets侧发送过来的端口
					h5Port.onmessage = function (event) {
						// 2. 接收ets侧发送过来的消息.
						var msg = 'Got message from ets:';
						var result = event.data;
						if (typeof result == 'string') {
							msg = msg + result;
						} else if (typeof msg == 'object') {
							if (msg instanceof ArrayBuffer) {
								msg = msg + `ArrayBuffer length: ${msg.byteLength}`;
							} else {
								console.log('not support');
							}
						} else {
							console.log('not support');
						}
						console.log(msg);
						output.innerHTML = msg;
					};
				}
			}
		});

		// 3. 使用h5Port往ets侧发送消息.
		function PostMsgToEts(data = 'message from HTML') {
			if (h5Port) {
				h5Port.postMessage(data);
			} else {
				console.error('h5Port is null, Please initialize first');
			}
		}
	</script>
</html>
